package com.qining618.cms.cms.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qining618.cms.cms.controller.admin.request.AdminContentEditRequest;
import com.qining618.cms.cms.controller.admin.request.AdminContentSetTopLevelRequest;
import com.qining618.cms.cms.domain.Content;
import com.qining618.cms.cms.service.ContentService;
import com.qining618.common.annotation.Access;
import com.qining618.common.context.ContextHandle;
import com.qining618.common.result.ApiResult;
import com.qining618.common.result.TableData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Description;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>
 * CMS内容 前端控制器
 * </p>
 *
 * @author qining
 * @date 2019-09-17
 */
@RestController
@RequestMapping("/admin/api/cms/content")
public class AdminContentController {

    @Autowired
    private ContentService contentService;

    @Access(needAdmin = true)
    @GetMapping(value = "page")
    @Description("分页")
    public ApiResult page(@RequestParam Map<String, Object> params) {
        IPage<Content> pageInfo = contentService.page(params);

        return ApiResult.ok(TableData.of(pageInfo));
    }

    @Access(needAdmin = true)
    @PostMapping
    @Description("添加")
    public ApiResult add(@RequestBody @Validated AdminContentEditRequest contentEditRequest) {
        Long userId = ContextHandle.getUserId();
        Content content = contentService.save(contentEditRequest.toContent(), userId,
                contentEditRequest.getDraft(), contentEditRequest.getContribute(),
                contentEditRequest.getChannelIds());
        return ApiResult.ok(content);
    }

    @Access(needAdmin = true)
    @PutMapping(value = "{id}")
    @Description("修改")
    public ApiResult edit(
            @PathVariable(value = "id") Long id,
            @RequestBody @Validated AdminContentEditRequest contentEditRequest) {
        Long userId = ContextHandle.getUserId();
        Content content = contentEditRequest.toContent();
        content.setId(id);
        content = contentService.save(content, userId, contentEditRequest.getDraft(), contentEditRequest.getContribute(),
                contentEditRequest.getChannelIds());
        return ApiResult.ok(content);
    }

    @Access(needAdmin = true)
    @PutMapping(value = "{id}/topLevel")
    @Description("设置置顶")
    public ApiResult setTopLevel(
            @PathVariable(value = "id") Long id,
            @RequestBody @Validated AdminContentSetTopLevelRequest setTopLevelRequest) {
        this.contentService.setTopLevel(id, setTopLevelRequest.getLevel(), setTopLevelRequest.getDueTime());
        return ApiResult.ok();
    }
}

